(function ($app) {
    $app.module('gtPartyApp').controller('taskpubeditCtrl', function ($scope, $http, $modal, $excel, $ocLazyLoad, $alert, $loading, $state, $partySelect, $stateParams, $bsRouterState) {
        $stateParams = $bsRouterState.$params($scope);
        $scope.isDetail = ($stateParams.isDetail == "true" || $stateParams.isDetail == true);

        $scope.maxDate = moment(new Date()).format("YYYY-MM-DD");

        //定义数据集合
        $scope.flowModel = {
            flowid: $stateParams.flowId == undefined ? "" : $stateParams.flowId,
            joinuserid: $stateParams.joinUserId == undefined ? "" : $stateParams.joinUserId
        };
        $scope.userModel = {};
        $scope.dataModel = {applyid: ''};
        $scope.userList = [];
        $scope.reqFileModel = {
            selectdata: {FileRefID: '', pageindex: 1, pagesize: 10, ptotal: 0},//查询参数：FileRefID为文件关联ID
            filetype: 3,//文件类型
            items: [],//列表数据地址
            readonly: !$scope.isDetail,//是否只能查看
            title: '附件',
            addFileButton: '上传'
        };
        $scope.userType = [{dickey: "组织助理员", dicvalue: "1"}, {dickey: "宣传助理员", dicvalue: "2"},
            {dickey: "纪检监察员", dicvalue: "3"}, {dickey: "党群办主任", dicvalue: "4"}, {dickey: "综合部（党群工作部）部长", dicvalue: "5"},
            {dickey: "党委书记", dicvalue: "6"}];
        //选择成员
        $scope.selectUserlist = {
            url: '../../api/partyTowExt/getleaderUserList',
            title: '人员选择',
            isMulti: true,
            selectData: {username: '姓名'},
            columns: {XM: '姓名', DZZMC: '所在组织架构'},
            selectLabelKey: 'XM',
            selectValuekey: 'RYBM',
            comboxData: {usertype: {text: '人员类型', data: $scope.userType}},
            selectedValueData: '',
            selectedLabeData: '',
            selectedJData: [],
            selectParams: {
                dzzdm: "",
                removeUserRybm: ''
            }
        };
        $scope.$watch('selectUserlist.selectedValueData', function (newVal) {
            if (newVal != '' && newVal != undefined) {
                $http({
                    method: 'get',
                    url: '../../api/partyUser/getPartyUserList',
                    params: {
                        rybm_list: newVal,
                        pageindex: 1,
                        pagesize: 10000
                    }
                }).then(function (result) {
                    $loading.hide();
                    angular.forEach(result.data.item.list, function (val, key) {
                        var data = $scope.userList.filter(function (item) {
                            return item.userid == val.RYBM
                        })
                        if (data.length == 0) {
                            $scope.userList.push({
                                username: val.XM,
                                userid: val.RYBM,
                                dzzmc: val.DZZMC,
                                dzzdm: val.SZDZBDM
                            });
                        }
                    });
                    $scope.selectUserlist.selectedValueData = "";
                    $scope.selectUserlist.selectedLabeData = "";
                }, function (resp) {
                    $loading.hide();
                    $scope.showMsg('错误', '服务器错误');
                });
            }
        });
        $scope.$watch('userList', function (newVal) {
            $scope.setRemoveUser();
        }, true);
        $scope.setRemoveUser = function () {
            $scope.selectUserlist.selectParams.removeUserRybm = "";
            angular.forEach($scope.userList, function (val, index) {
                $scope.selectUserlist.selectParams.removeUserRybm += val.USERCODE + ','
            });
        };

        $scope.loadData = function () {
            $http.get("../../api/partyTowExt/getTask", {
                params: {
                    'id': $stateParams.id
                }
            }).then(function (result) {
                $scope.dataModel = result.data.item;
                $scope.reqFileModel.selectdata.FileRefID = result.data.item.id;
                $scope.reqFileModel.selectdata.userId = result.data.item.createuserid;
                $scope.getUserList($scope.dataModel.id);
                $scope.getcolumnList($scope.dataModel.id);
            }, function () {
                $scope.showMsg('错误', '服务器错误');
            });
        };

        //保存
        $scope.submitData = function (isflag) {
            if ($scope.userList.length == 0) {
                $scope.showMsg('提示', '至少选择一个接收人');
                return false;
            }
            if ($scope.columnList.length == 0) {
                $scope.showMsg('提示', '至少新增一个字段');
                return false;
            }
            //验证列名是否有重复
            var isRepeat = false;
            for (index in $scope.columnList) {
                var collist = $scope.columnList.filter(function (col) {
                    return $scope.columnList[index].columnname == col.columnname;
                })
                if (collist.length > 1) {
                    isRepeat = true;
                    break;
                }
            }
            if (isRepeat) {
                $scope.showMsg('提示', '字段名称不允许重复');
                return false;
            }
            if (isflag) {
                //数据处理
                var userList = [];
                angular.forEach($scope.userList, function (val, key) {
                    userList.push({
                        id: val.ID,
                        userid: val.userid,
                        username: val.username,
                        dzzdm: val.dzzdm,
                        dzzmc: val.dzzmc,
                    });
                });

                if (confirm("确认提交？")) {
                    $loading.show();
                    $scope.dataModel.tasktype = 2;
                    $http({
                        method: "post",
                        url: "../../api/partyTowExt/saveTask",
                        data: {
                            dataModel: $scope.dataModel,
                            userList: JSON.stringify(userList),
                            columnList: JSON.stringify($scope.columnList),
                            flowId: $scope.flowModel.flowid
                        }
                    }).then(function (result) {
                        $loading.hide();
                        if (result.data.success) {
                            $scope.showMsg('成功', result.data.msg);
                            $scope.$emit("tabReloadData", {name: 'taskCtrl', data: 1});
                            //重新刷新列表
                            $scope.pagechange();

                        } else {
                            $scope.showMsg('失败', result.data.msg);
                        }

                    }, function (resp) {
                        $scope.showMsg('错误', '服务器错误');
                    });
                }
            }
        };

        $scope.addUser = function () {
            //$scope.userList.push({});
        };

        $scope.delUser = function (index) {
            $scope.userList.splice(index, 1);
        };

        $scope.columnList = [];

        $scope.invalidFee = function (index, form1, name) {
            name = name + "_" + index;
            eval('var i=form1.' + name + '.$invalid');
            return i;
        };

        $scope.getUserList = function (taskid) {
            $http
            ({
                method: 'get', url: '../../api/partyTowExt/getTaskUserList', params: {
                    pageindex: 1,
                    pagesize: 1000, taskid: taskid
                }
            }).then(function (result) {
                $scope.userList = result.data.item;
            });
        };

        //选择成员
        $scope.selectTaskTemplateList = {
            url: '../../api/taskpub/getEnableTemplateList',
            title: '模板选择',
            isMulti: false,
            selectData: {tempName: '模板名称'},
            columns: {TEMPNAME: '模板名称', COLUMNNUMBER: '字段数量'},
            selectLabelKey: 'TEMPNAME',
            selectValuekey: 'TASKTEMPID',
            selectedValueData: '',
            selectedLabeData: '',
            selectedJData: [],
            selectParams: {}
        };
        $scope.$watch('selectTaskTemplateList.selectedValueData', function (newVal) {
            if (newVal != '' && newVal != undefined) {
                $http({
                    method: 'get',
                    url: '../../api/taskpub/getTasktempColumnList',
                    params: {
                        taskid: newVal,
                        pageindex: 1,
                        pagesize: 10000
                    }
                }).then(function (result) {
                    $loading.hide();
                    angular.forEach(result.data.item, function (val, key) {
                        var data = $scope.columnList.filter(function (item) {
                            return item.tasktempcolid == val.tasktempcolid
                        })
                        if (data.length == 0) {
                            $scope.columnList.push(val);
                        }
                    });
                    $scope.selectTaskTemplateList.selectedValueData = "";
                    $scope.selectTaskTemplateList.selectedLabeData = "";
                }, function (resp) {
                    $loading.hide();
                    $scope.showMsg('错误', '服务器错误');
                });
            }
        });

        $scope.addRow = function () {
            $scope.columnList.push({isRequired: "1"});
        };

        $scope.delRow = function (index) {
            $scope.columnList.splice(index, 1);
        };

        $scope.invalidColumn = function (index, form1, name) {
            name = name + "_" + index;
            eval('var i=form1.' + name + '.$invalid');
            return i;
        };
        $scope.taskColumnTypeList = [];
        $scope.getTaskColumnTypeList = function () {
            $http({
                method: 'get',
                url: '../../api/dictionary/getDictionaryListByDicTypeKey',
                params: {
                    dicTypeKey: 'TaskColumnType'
                }
            }).then(function (result) {
                $scope.taskColumnTypeList = result.data;
            }, function (resp) {

            });
        };
        $scope.getTaskColumnTypeList();

        $scope.getcolumnList = function (taskid) {
            $http
            ({
                method: 'get', url: '../../api/taskpub/getTaskpubcolumnList', params: {
                    pageindex: 1,
                    pagesize: 1000, taskid: taskid
                }
            }).then(function (result) {
                $scope.columnList = $scope.columnList.concat(result.data.item);
            });
        };

//导入
        $scope.excelConfig = {
            filetype: 1,
            columns: {
                '字段名称': 'columnname',
                '字段类型': 'taskcolumntype',
                '输入提示': 'tips',
                '是否必填': 'isrequired'
            },
            errorcolumns: {
                'columnname': '字段名称',
                'taskcolumntype': '字段类型',
                'tips': '输入提示',
                'isrequired': '是否必填',
                'errorInfo': '错误信息'
            },
            readonly: false,
            templateUrl: '../../doc/template/收集信息字段导入模板.xlsx'
        };
        $scope.import = function () {
            $excel.addFile($scope.excelConfig).then(function (items) {
                $loading.show();
                $http({
                    method: "post",
                    url: "../../api/taskpub/importTaskpubcolumn",
                    data: {
                        userList: JSON.stringify(items),
                        'id': $scope.dataModel.id
                    }
                }).then(function (result) {
                    $loading.hide();
                    if (result.data.success) {
                        $scope.showMsg('成功', result.data.msg, 3);
                        $scope.getcolumnList($scope.dataModel.id);
                    } else {
                        if (result.data.item.length > 0) {
                            $excel.showErrorInfo(result.data.item);
                        }
                    }

                }, function (resp) {
                    $loading.hide();
                    $scope.showMsg('错误', '服务器错误');
                })
            });
        };

        $scope.loadData();

        $scope.pagechange = function () {
            var inTab = $bsRouterState.$getRouteType() == 'tab';
            if (inTab) {
                $bsRouterState.$closeTab($scope);
            } else {
                window.history.back();
            }
        };
        $scope.reset = function (id) {
            if (confirm("是否确定让该人员再次提交任务？")) {
                $http.get("../../api/partyTowExt/resetSubmit", {
                    params: {
                        'id': id
                    }
                }).then(function (result) {
                    $scope.showMsg('提示', "已重新提交");
                    $scope.getUserList($scope.dataModel.id);
                }, function () {
                    $scope.showMsg('错误', '服务器错误');
                });
            }
        };
        $scope.showMsg = function (title, content) {
            $alert({
                title: title + '：',
                content: content,
                placement: 'top',
                type: 'info',
                show: true,
                duration: 3
            });

        };

    });
})(angular);
